package com.woniuxy.amusementparkos.controller.fzw;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.woniuxy.amusementparkos.entity.fzw.User;
import com.woniuxy.amusementparkos.exception.fzw.UserException;
import com.woniuxy.amusementparkos.service.fzw.UserService;
@Controller
public class LoginAndRegisterController {
	private static final Logger logger = LoggerFactory.getLogger(LoginAndRegisterController.class);
	@Autowired
	UserService userService;
	
	@RequestMapping("/login")
	public ModelAndView login(User user) {
		ModelAndView mv = new ModelAndView();
		//获取当前用户
		Subject subject = SecurityUtils.getSubject();
		//创建令牌
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
		try {			
			subject.login(token);
			//若上面login检查没有异常则说明账号密码正确，则存入session账号信息
			mv.addObject("user", user.getUsername());
			User realuser = userService.selectOneUserByName(user.getUsername());
			//查询用户具有的菜单管理
			List<String> menus = userService.selectMenusByUserId(realuser.getUser_id());
			mv.addObject("account",realuser.getAccount());
			mv.addObject("menus",menus);
		} catch (UnknownAccountException e) {
			mv.addObject("msg", "用户名或密码错误");
		} catch (IncorrectCredentialsException e) {
			mv.addObject("msg", "用户名或密码错误");
		} 
		catch (Exception e) {
			mv.addObject("msg", "未知错误");
		}
		mv.setViewName("/backstage");
		return mv;
	}
	
	/**
	 * 注册模块，暂时不需要，最后根据项目情况完善
	 * @param user
	 * @return
	 */
	@RequestMapping("/user/register.do")
	@ResponseBody
	public ModelAndView register(User user) {
		ModelAndView mv = new ModelAndView();
		String username=user.getUsername();
		String account=user.getAccount();
		String password=user.getPassword();
		
		//注册验证
		try {
			userService.register(user);
		} catch (UserException e) {
			mv.setViewName("/");
		} 
		//验证无误后跳转
		
		return mv;
	}
	@RequestMapping("/user/userManagement")
	public ModelAndView toUserManagement() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/fzw/userManagement"); 
		return mv;
	}
	@RequestMapping("/user/roleManagement")
	public ModelAndView toRoleManagement() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/fzw/roleManagement.html"); 
		return mv;
	}
	@RequestMapping("/user/organizationManagement")
	public ModelAndView toOrganizationManagement() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/fzw/organizationManagement");
		return mv;
	}
}